<template>
  <div class="" style="padding: 2rem">
    <div style="display: flex; align-items: center">
      <a-image width="40" src="/logo.png" />
      <h3 style="margin-left: 10px">会议报表</h3>
    </div>
    <div>
      <div
        ref="chartDom"
        style="width: 130vm; height: 60vh; margin-top: 20px"
      ></div>
    </div>
    <!-- 添加缺席详情弹窗 -->
    <a-modal
      v-model:visible="showAbsenceDetail"
      :title="`${selectedUser}缺席您的如下会议`"
      @cancel="showAbsenceDetail = false"
    >
      <a-table
        :columns="absenceDetailColumns"
        :data="selectedAbsences"
        :pagination="false"
      />
    </a-modal>
    <!-- 会议详情弹窗 -->
    <a-modal
      v-model:visible="detailVisible"
      :title="meetDetail?.subject"
      :width="800"
      :footer="false"
      unmount-on-close
      @cancel="detailVisible = false"
      @ok="detailVisible = false"
    >
      <div v-if="meetDetail" class="meet-detail">
        <div class="detail-item">
          <span class="label">会议号：</span>
          <span class="value">{{ meetDetail.conferenceId }}</span>
        </div>
        <div class="detail-item">
          <span class="label">会议主题：</span>
          <span class="value">
            <div class="subject-detail">{{ meetDetail.subject }}</div>
          </span>
        </div>
        <div class="detail-item">
          <span class="label">会议室：</span>
          <span class="value">{{ meetDetail.meetingRoomName || '线上会议' }}</span>
        </div>
        <div class="detail-item">
          <span class="label">会议时间：</span>
          <span class="value">{{ meetDetail.startTime }} - {{ meetDetail.endTime }}</span>
        </div>
        <div class="detail-item">
          <span class="label">会议状态：</span>
          <span class="value">
            <a-tag :color="getStatusColor(meetDetail.conferenceState)">
              {{ getStatusText(meetDetail.conferenceState) }}
            </a-tag>
          </span>
        </div>
        <div class="detail-item">
          <span class="label">会议类型：</span>
          <span class="value">
            {{ meetDetail.meetType === 0 ? '线下' : '线上' }}
            <a-tag v-if="meetDetail.circleType === 1" color="blue" class="ml-2">周期会议</a-tag>
          </span>
        </div>
        <div class="detail-item">
          <span class="label">会议配置：</span>
          <div class="value">
            <div class="config-item">
              <a-tag :color="getCallInRestrictionColor(meetDetail.callInRestriction)">
                {{ getCallInRestrictionText(meetDetail.callInRestriction) }}
              </a-tag>
            </div>
            <div class="config-item">
              <a-tag :color="meetDetail.enableWaitingRoom ? 'blue' : 'gray'">
                {{ meetDetail.enableWaitingRoom ? '开启等候室' : '关闭等候室' }}
              </a-tag>
            </div>
            <div class="config-item">
              <a-tag :color="meetDetail.autoMute === 1 ? 'blue' : 'gray'">
                {{ meetDetail.autoMute === 1 ? '自动静音' : '不自动静音' }}
              </a-tag>
            </div>
          </div>
        </div>
        <div v-if="meetDetail.circleType === 1" class="detail-item">
          <span class="label">周期信息：</span>
          <div class="value">
            <div v-for="(monthGroup, index) in meetDetail.subMeet" :key="index" class="sub-meet-group">
              <div class="month-title">{{ monthGroup.month }}</div>
              <div class="sub-meet-list">
                <div v-for="sub in monthGroup.sub" :key="sub.id" class="sub-meet-item">
                  <div class="sub-meet-time">{{ sub.startTime }} - {{ sub.endTime }}</div>
                  <div class="sub-meet-subject">{{ sub.subject }}</div>
                  <div class="sub-meet-creator">创建人：{{ sub.createUserName }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="detail-item">
          <span class="label">主持人密码：</span>
          <span class="value">{{ meetDetail.passwordChair }}</span>
        </div>
        <div class="detail-item">
          <span class="label">来宾密码：</span>
          <span class="value">{{ meetDetail.passwordGeneral || '无' }}</span>
        </div>
        <div class="detail-item">
          <span class="label">创建人：</span>
          <span class="value">{{ meetDetail.createUserName }}</span>
        </div>
        <div class="detail-item">
          <span class="label">参会人：</span>
          <div class="value">
            <div class="participants">
              <div v-for="participant in visibleParticipants" :key="participant.userid" class="participant-item">
                <a-avatar
                  :size="32"
                  :image-url="participant.avatar"
                  class="participant-avatar"
                >
                  {{ participant.realname?.charAt(0) }}
                </a-avatar>
                <span class="participant-name">{{ participant.realname }}</span>
              </div>
            </div>
            <a-button v-if="hasMoreParticipants" type="outline" size="small" class="view-more-btn" @click="allParticipantsVisible = true">
              <template #icon><IconMore /></template>
              查看全部
            </a-button>
          </div>
        </div>
        <div class="detail-item">
          <span class="label">创建时间：</span>
          <span class="value">{{ meetDetail.createTime }}</span>
        </div>
        <div class="detail-item">
          <span class="label">更新时间：</span>
          <span class="value">{{ meetDetail.updateTime }}</span>
        </div>
      </div>
    </a-modal>

    <!-- 全部参会人弹窗 -->
    <a-modal
      v-model:visible="allParticipantsVisible"
      title="全部参会人员"
      :width="700"
      :footer="false"
      @cancel="allParticipantsVisible = false"
    >
      <div class="all-participants">
        <div v-for="participant in meetDetail?.participants" :key="participant.userid" class="participant-item">
          <a-avatar
            :size="36"
            :image-url="participant.avatar"
            class="participant-avatar"
          >
            {{ participant.realname?.charAt(0) }}
          </a-avatar>
          <span class="participant-name">{{ participant.realname }}</span>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue'
import * as echarts from 'echarts'
import { Message } from '@arco-design/web-vue'
import { IconMore } from '@arco-design/web-vue/es/icon'
import { getMeetAbsentUser } from '@/apis/meet/component'
import { getMeet } from '@/apis/meet/meet'

interface ConferenceAbsenceDTO {
  conferenceId: string
  meetName: string
}

interface AbsenceRankingDTO {
  username: string
  absenceCount: number
  absences: ConferenceAbsenceDTO[]
}

const chartDom = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null
const absentClassList = ref<AbsenceRankingDTO[]>([]) // 缺席人列表
const showAbsenceDetail = ref(false)
const selectedUser = ref('')
const selectedAbsences = ref<ConferenceAbsenceDTO[]>([])
const detailVisible = ref(false)
const meetDetail = ref<any>(null)
const allParticipantsVisible = ref(false)
const PARTICIPANTS_LIMIT = 6

// 获取会议状态文本
const getStatusText = (conferenceState: number) => {
  const statusMap: Record<number, string> = {
    0: '预约',
    1: '已开始',
    2: '取消',
    3: '结束'
  }
  return statusMap[conferenceState] || '未知状态'
}

// 获取会议状态颜色
const getStatusColor = (conferenceState: number) => {
  const statusMap: Record<number, string> = {
    0: 'orange',
    1: 'green',
    2: 'red',
    3: 'red'
  }
  return statusMap[conferenceState] || 'default'
}

// 计算显示的参会人列表
const visibleParticipants = computed(() => {
  if (!meetDetail.value?.participants) return []
  return meetDetail.value.participants.slice(0, PARTICIPANTS_LIMIT)
})

// 检查是否需要显示"查看更多"按钮
const hasMoreParticipants = computed(() => {
  return meetDetail.value?.participants && meetDetail.value.participants.length > PARTICIPANTS_LIMIT
})

// 获取入会范围文本
const getCallInRestrictionText = (callInRestriction: number) => {
  const restrictionMap: Record<number, string> = {
    0: '所有用户',
    2: '企业内用户',
    3: '被邀请用户'
  }
  return restrictionMap[callInRestriction] || '未知范围'
}

// 获取入会范围颜色
const getCallInRestrictionColor = (callInRestriction: number) => {
  const colorMap: Record<number, string> = {
    0: 'green',
    2: 'blue',
    3: 'orange'
  }
  return colorMap[callInRestriction] || 'gray'
}

// 显示会议详情
const showMeetDetail = async (record: any) => {
  try {
    const res = await getMeet(record.conferenceId)
    if (Number(res.code) === 0 && res.data) {
      meetDetail.value = res.data
      detailVisible.value = true
    } else {
      Message.error(res.msg || '获取会议详情失败')
    }
  } catch (error: any) {
    console.error('获取会议详情错误:', error)
    Message.error(error.message || '获取会议详情失败')
  }
}

const absenceDetailColumns = [
  {
    title: '会议名称',
    dataIndex: 'meetName',
    render: ({ record }) => {
      return h(
        'a',
        {
          onClick: () => {
            showMeetDetail(record)
          },
          style: {
            'color': '#165DFF',
            'cursor': 'pointer',
            '&:hover': {
              color: '#0E42D2'
            }
          }
        },
        record.meetName
      )
    }
  },
  {
    title: '会议ID',
    dataIndex: 'conferenceId'
  }
]

const updateChart = () => {
  if (!chartInstance) return

  const option = {
    title: {
      text: '我的会议参会人缺席次数统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter(params: any) {
        return `${params.name}: ${params.value}次缺席`
      }
    },
    xAxis: {
      type: 'category',
      data: absentClassList.value.map((item) => item.username),
      axisLabel: {
        formatter: (value: string) => {
          const maxLength = 5
          return value.length > maxLength
            ? `${value.slice(0, maxLength)}...`
            : value
        },
        interval: 0,
        color: '#666',
        fontSize: 12,
        margin: 15
      }
    },
    yAxis: {
      type: 'value',
      name: '缺席次数'
    },
    series: [
      {
        type: 'bar',
        data: absentClassList.value.map((item) => item.absenceCount),
        itemStyle: {
          color: '#1890ff'
        },
        emphasis: {
          itemStyle: {
            color: '#40a9ff'
          }
        }
      }
    ]
  }

  chartInstance.setOption(option)

  // 添加点击事件
  chartInstance.off('click')
  chartInstance.on('click', (params: any) => {
    const userData = absentClassList.value[params.dataIndex]
    selectedUser.value = userData.username
    selectedAbsences.value = userData.absences
    showAbsenceDetail.value = true
  })
}

const getAbsenceData = async () => {
  const res = await getMeetAbsentUser()
  absentClassList.value = res.data
  updateChart()
}

onMounted(async () => {
  await getAbsenceData()
  nextTick(() => {
    chartInstance = echarts.init(chartDom.value)
    updateChart()
  })
})

onUnmounted(() => {
  if (chartInstance != null && chartInstance.dispose) {
    chartInstance.dispose()
  }
})
</script>

<style lang="scss" scoped>
.meet-detail {
  padding: 16px;

  .detail-item {
    margin-bottom: 16px;
    display: flex;
    align-items: flex-start;

    .label {
      width: 100px;
      color: var(--color-text-2);
      font-weight: 500;
    }

    .value {
      flex: 1;
      color: var(--color-text-1);

      .ml-2 {
        margin-left: 8px;
      }

      .config-item {
        display: inline-block;
        margin-right: 12px;
        margin-bottom: 8px;

        &:last-child {
          margin-right: 0;
        }
      }

      .sub-meet-group {
        margin-bottom: 16px;
        padding: 12px;
        background-color: var(--color-fill-2);
        border-radius: 4px;

        .month-title {
          font-size: 16px;
          font-weight: 500;
          color: var(--color-text-1);
          margin-bottom: 12px;
          padding-bottom: 8px;
          border-bottom: 1px solid var(--color-border);
        }

        .sub-meet-list {
          display: flex;
          flex-direction: column;
          gap: 12px;

          .sub-meet-item {
            padding: 12px;
            background-color: var(--color-bg-2);
            border-radius: 4px;
            transition: all 0.2s;

            &:hover {
              background-color: var(--color-fill-3);
              transform: translateY(-2px);
            }

            .sub-meet-time {
              font-size: 14px;
              color: var(--color-text-1);
              margin-bottom: 4px;
            }

            .sub-meet-subject {
              font-size: 14px;
              color: var(--color-text-1);
              margin-bottom: 4px;
            }

            .sub-meet-creator {
              font-size: 12px;
              color: var(--color-text-3);
            }
          }
        }
      }

      .participants {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 16px 20px;
        margin-bottom: 12px;
        width: 100%;

        .participant-item {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 8px 12px;
          border-radius: 4px;
          background-color: var(--color-fill-2);
          transition: all 0.2s;

          &:hover {
            background-color: var(--color-fill-3);
            transform: translateY(-2px);
          }

          .participant-avatar {
            cursor: pointer;
            flex-shrink: 0;
          }

          .participant-name {
            font-size: 14px;
            color: var(--color-text-1);
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }

      .view-more-btn {
        margin-top: 10px;
        transition: all 0.2s;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
        }
      }
    }
  }
}

.all-participants {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  max-height: 60vh;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 8px;
  width: 100%;
  box-sizing: border-box;

  .participant-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 8px 12px;
    border-radius: 4px;
    background-color: var(--color-fill-2);
    transition: all 0.2s;
    width: 100%;
    box-sizing: border-box;
    word-break: break-all;

    &:hover {
      background-color: var(--color-fill-3);
      transform: translateY(-2px);
    }

    .participant-avatar {
      cursor: pointer;
      flex-shrink: 0;
    }

    .participant-name {
      font-size: 14px;
      color: var(--color-text-1);
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>
